package com.aisino.wxkp.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.aisino.wxkp.common.basic.WxkpBaseAction;
import com.aisino.wxkp.common.config.Constants;
import com.aisino.wxkp.common.entity.DecrySmCAInfo;
import com.aisino.wxkp.common.entity.FpWxFpmx;
import com.aisino.wxkp.common.entity.JsAeroInfoReturnException;
import com.aisino.wxkp.common.entity.JsonRespon;
import com.aisino.wxkp.common.entity.ResponseInfo;
import com.aisino.wxkp.common.enums.RCodeEnums;
import com.aisino.wxkp.common.enums.ReqQyxx;
import com.aisino.wxkp.common.fpkj.dto.B_ReturnStateInfo;
import com.aisino.wxkp.common.fpkj.dto.InterfaceXML;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpcx;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkj;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkjFptxx;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkjFpxxNew;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkjXmxx;
import com.aisino.wxkp.common.util.Base64G;
import com.aisino.wxkp.common.util.HxJSONUtils;
import com.aisino.wxkp.common.util.InvParseO2X;
import com.aisino.wxkp.common.util.InvParseX2O;
import com.aisino.wxkp.common.util.StringUtil;
import com.aisino.wxkp.service.GooAGooService;
import com.aisino.wxkp.service.WXKPService;
import com.aisino.wxkp.service.impl.GooAGooServiceImpl;
import com.aisino.wxkp.service.impl.WXKPServiceImpl;
import com.aisino.xstream.helper.Base64Helper;
import com.thoughtworks.xstream.XStream;

public class WXTransDataAction extends WxkpBaseAction {
	private static final long serialVersionUID = 1L;
	WXKPService wxkpInvService = new WXKPServiceImpl();
	GooAGooService gagInvService = new  GooAGooServiceImpl();
	private static final Logger LOGGER = Logger.getLogger(WXTransDataAction.class);

	public void WXKP(HttpServletRequest request,HttpServletResponse response) throws JsAeroInfoReturnException, Exception {
		try{
			String c = request.getParameter("c");		// c 客户类型 固定为1000
			String t = request.getParameter("t");		// t 开具类型 1为蓝票，2为红冲
			String id = request.getParameter("id");		// ID 发票流水号   BASE64加密：其中+/分别替换为-_  去除=
			String fpqqlsh = deReplaceBase64(id);
			String nsrsbh ="";
			String ik = request.getParameter("ik");		// IK 二维码校验符
			String uid = request.getPareter("pwd");	//	PWD	平台注册密码
			String billid = requeameter("uid");	//	UID 平台注册用户名
			String pwd = request.getParamst.getParameter("billid")==null?"":request.getParameter("billid");
			DecrySmCAInfo caInfo = null;
			XStream xStream = new XStream();
			String returnURL = "";
			String qymc = "";
			String password = "";
			String authorizationcode = "";
			if (!"1000".equals(c)) {
				throw new JsAeroInfoReturnException("404", "页面访问失败!");
			}
			if (StringUtil.validateNull(fpqqlsh) || StringUtil.validateNull(t) || StringUtil.validateNull(c)
					|| StringUtil.validateNull(uid) || StringUtil.validateNull(pwd)) {
				throw new JsAeroInfoReturnException("9999", "页面信息校验失败!");
			}
			// 平台验证
			if(billid != "" ){
				Map<String, Object> paraMap =  gagInvService.queryXfsh(billid);
				fpqqlsh = (String) paraMap.get("fpqqlsh");
				nsrsbh = (String) paraMap.get("nsrsbh");
				returnURL = (String) paraMap.get("returnURL");
				qymc = (String) paraMap.get("qymc");
				password = (String) paraMap.get("password");
				authorizationcode = (String) paraMap.get("authorizationcode");
			}else{
				String DecrySmCA = Base64G.decode2(postClServerRequest("", Constants.TransferServicePr_queryGlobal_url+"?username="+uid+"&pwd="+pwd));
				xStream.alias("root", DecrySmCAInfo.class);
				caInfo = (DecrySmCAInfo) xStream.fromXML(DecrySmCA);
				nsrsbh = caInfo.getTaxpayerid();
				returnURL = ReqQyxx.getQyURL(String.valueOf(caInfo.getId()));
				qymc=caInfo.getUsername();
				password= caInfo.getPassword();
				authorizationcode= caInfo.getAuthorizationcode();
			}
			// 是否开具 
			JsonRespon hasfp = wxkpInvService.validHasOpenInv(nsrsbh,fpqqlsh);
			if (RCodeEnums.E9999.getCode().equals(hasfp.getCode())) {
				Object obj_t = hasfp.getData();
				if (obj_t != null) {
					JshxTblFpcx fpcxObj = new JshxTblFpcx();
					JshxTblFpcx obj = (JshxTblFpcx) obj_t;
					JshxTblFpkjFpxxNew ykfp = obj.getYkfp();
					JshxTblFpkjFptxx fptxx = obj.getFptxx();
					StringBuffer fpdurl = new StringBuffer();
//					System.out.println("发票代码=="+ykfp.getFpDm()+"发票号码=="+ykfp.getFpHm()+"请求流水号=="+ykfp.getFpqqlsh());
					fpdurl.append("?fpdm=").append(
							Base64Helper.encode(ykfp.getFpDm()));
					fpdurl.append("&fphm=").append(
							Base64Helper.encode(ykfp.getFpHm()));
					fpdurl.append("&qqlsh=").append(
							Base64Helper.encode(ykfp.getFpqqlsh()));
					ykfp.setPdfUrl(Constants.DOWN_PDF_URL_ROOT
							+ fpdurl.toString());
					ykfp.setByzd1("/invoice/img/"+nsrsbh+".jpg");
					if (ykfp != null) {
						if (!fpqqlsh.equals(ykfp.getFpqqlsh())) {
							throw new JsAeroInfoReturnException("9998",
									"类型校验不一致!");// 已开具页面
							}
						fpcxObj.setYkfp(ykfp);
						fpcxObj.setFptxx(fptxx);
					/*******************回写*********************/
				if(!nsrsbh.equals("91320311MA1P3GWX59")){
					if (!StringUtil.validateNull(ykfp.getFpDm()) && !StringUtil.validateNull(ykfp.getFpHm())) {
						if("1".equals(fptxx.getErpRetCode())){
						final String dataContent = InvParseO2X.getReturnService(fpcxObj);
						String respxml = reqReturnMSG(qymc, password, authorizationcode, nsrsbh, Base64G.encode2(dataContent), returnURL);
						 InterfaceXML inter = InvParseX2O.getInterfaceObj(respxml);
						 if(inter!= null){
						 B_ReturnStateInfo RetInfo = inter.getReturnStateInfo();
						 String resMsg = RetInfo.getReturnMessage();
						 System.out.println("回写状态	"+Base64G.decode2(resMsg));
						//更改回写状态
						 ResponseInfo retInfo = wxkpInvService.updateRetStatus("3",nsrsbh,fpqqlsh);
						 System.out.println(retInfo.getReturncode()+Base64G.decode2(retInfo.getReturnmessage()));
						 		}
							}
						}
					}
					/************************************************/
					
					LOGGER.info("发票已经生成");
					request.getSession().setAttribute("invoiceInfo", fpcxObj);
					request.getRequestDispatcher("/test/reqFpkj.jsp").forward(request,response);
					}
				}else {
					throw new JsAeroInfoReturnException("9999", "开票对象返回为空");
				}
			}else if(RCodeEnums.E8899.getCode().equals(hasfp.getCode())){
					Object obj_t = hasfp.getData();	
					JshxTblFpcx fpcxObj =(JshxTblFpcx)obj_t;
					JshxTblFpkjFptxx fpttxx = (JshxTblFpkjFptxx) fpcxObj.getFptxx();
					fpttxx.setGhfmc(fpttxx.getGhfmc());
					fpttxx.setXhfmc(fpttxx.getXhfmc());
					fpttxx.setKphjje(fpttxx.getKphjje());
					fpttxx.setByzd1("/invoice/img/"+nsrsbh+".jpg");
					request.setAttribute("invoiceInfo", fpttxx);
					request.getRequestDispatcher("/test/reqFpsq.jsp").forward(request,response);
			}else {
					LOGGER.info("发票未生成");
					Map<String, Object> DataMap = wxkpInvService.reqTransData(t,nsrsbh,fpqqlsh,ik,billid);
					JshxTblFpkj xxfpobj = (JshxTblFpkj) DataMap.get("fpkjobj");
					System.out.println("销方税号=="+xxfpobj.getFptt().getXhfNsrsbh());
					request.setAttribute("c", c);
					request.setAttribute("t", t);
					request.setAttribute("ic", nsrsbh);
					request.setAttribute("id", fpqqlsh);
					request.setAttribute("ik", ik);
					request.setAttribute("billid", billid);
					request.setAttribute("fpkjobj", xxfpobj);

					if ("1".equals(t)) {
						request.getRequestDispatcher("/test/kaipiao.jsp").forward(request,
								response);
					} else if ("2".equals(t)) {
						request.getRequestDispatcher("/test/hongpiao.jsp").forward(request,
								response);
					} else {
						request.getRequestDispatcher("404.jsp").forward(request,
								response);
					}
			}
		}
		catch (JsAeroInfoReturnException e) {
			try {
				request.setAttribute("errorcode", e.getCode());
				request.setAttribute("errorinfo", e.getMessage());
				request.getRequestDispatcher("error.jsp").forward(request,
						response);
			} catch (Exception e1) {
				response.sendRedirect("500.jsp");
			}
			return;
		} catch (Exception e) {
			e.printStackTrace();
			response.sendRedirect("500.jsp");
		}
	}

	public static void main(String[] args) {
		System.out.println(WxkpBaseAction.enReplaceBase64("A11801291e4i40003"));
//				System.out.println(WxkpBaseAction.deReplaceBase64("MzUxNzExMDhKNlgwMDA1MA"));
	}
}
